const search = (searchUser) => {
  let str = $('#header-search-input').val().trim();
  if (str && str != '') {
    let queryStr;
    if (searchUser) {
      queryStr = `user=${str}`;
    } else {
      queryStr = `channel=${str}`;
    }
    Router.go('explore', { name: 'search' }, {query: queryStr});
  } else {
    return;
  }
};

Template.header_search.onRendered(function() {
  this.elements = {
    input: $('#header-search-input'),
    button: $('#header-search-button'),
    dropdown: $('#header-search-dropdown'),
    userItem: $('#header-search-user-item')
  };
});

Template.header_search.events({
  'click #header-search-box'(event, instance) {
    event.stopPropagation();
  },
  'focus #header-search-input'(event, instance) {
    instance.elements.button.addClass('active');
    if (instance.elements.input.val() != '') {
      instance.elements.dropdown.dropdown('toggle');
    }
  },
  'blur #header-search-input'(event, instance) {
    instance.elements.button.removeClass('active');
  },
  'input #header-search-input'(event, instance) {
    let str = $.trim(event.target.value);
    if (str && str != '') {
      instance.elements.userItem.html(`搜索与 <strong>${str}</strong> 相关的用户`);
    }

    if (!instance.elements.userItem.parent().hasClass('show')) {
      instance.elements.dropdown.dropdown('toggle');
    }

    if (str.length === 0 || str == '') {
      instance.elements.userItem.html('');
      instance.elements.dropdown.dropdown('toggle');
    }
  },
  'keypress #header-search-input'(event, instance) {
    if (event.keyCode === 13) {
      event.preventDefault();
      search();
    }
  },
  'click #header-search-button'(event, instance) {
    instance.elements.input.trigger('focus');
    search();
  },
  'click #header-search-user-item'(event, instance) {
    event.preventDefault();
    search(true);
  },
});